package com.thinkgem.book.modules.sys.web;

import com.thinkgem.book.common.utils.Encodes;
import com.thinkgem.book.common.utils.RSAUtils;
import com.thinkgem.book.common.web.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.security.interfaces.RSAPublicKey;

/**
 * @author John
 * @Date 2016/4/19
 */
@Controller
public class ExportLicenseController extends BaseController{

    /**
     * 导出License
     * @return
     */
    @RequestMapping(value = "license")
    public String exportLicense() throws IOException{
        return "modules/sys/exportLicense";
    }

    /**
     * 导出License
     * @return
     */
    @RequestMapping(value = "license/export")
    public String exportFile(HttpServletResponse response, String licenseId, String beginDate, String endDate, Model model) throws IOException{
        OutputStream os = null;
        try {
            String fileName = "license.key";
            response.reset();
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setHeader("Content-Disposition", "attachment; filename="+ Encodes.urlEncode(fileName));
            os = response.getOutputStream();
            RSAPublicKey gongyao = RSAUtils.getDefaultPublicKey();
            String password = RSAUtils.encryptString(gongyao, licenseId + "|" + beginDate + "|" + endDate);
            if(StringUtils.isNotEmpty(password) && password.length() > 100){
                String temp = RSAUtils.getRandomString(500) + password + RSAUtils.getRandomString(500);
                os.write(temp.getBytes());
                os.close();
                response.flushBuffer();
            }
            else{
                model.addAttribute("message", "生成注册文件错误，请联系管理员！");
            }
        } catch (Exception e) {
            model.addAttribute("message", "生成注册文件错误，请联系管理员！");
            logger.error("生成注册文件时出错：", e);
        }finally{
            if(os != null){
                os.close();
            }
        }
        return "modules/sys/exportLicense";
    }
}
